<template>
  <div class="workbench-container">
    <!-- Header -->
    <el-header height="60px" class="header">
      <div class="header-left">
        <h2>智慧社区服务平台</h2>
      </div>
      <div class="header-right">
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">
            {{ username }}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-header>

    <!-- Main Container -->
    <el-container class="main-container">
      <!-- Sidebar -->
      <el-aside width="200px" class="aside">
        <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical-demo"
          @open="handleOpen"
          @close="handleClose"
          @select="handleSelect"
          background-color="#001529"
          text-color="#fff"
          active-text-color="#ffd04b"
          router
        >
          <el-submenu 
            :index="menu.id + ''" 
            v-for="menu in menuList" 
            :key="menu.id"
          >
            <template slot="title">
              <i :class="menu.icon"></i>
              <span>{{ menu.name }}</span>
            </template>
            <el-menu-item 
              v-for="child in menu.childrenMenu" 
              :key="child.id" 
              :index="child.link"
            >
              {{ child.name }}
            </el-menu-item>
          </el-submenu>
        </el-menu>
      </el-aside>

      <!-- Main Content -->
      <el-main class="main-content">
        <router-view></router-view>
      </el-main>
    </el-container>

    <!-- Change Password Dialog -->
    <el-dialog
      title="修改密码"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordForm"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="passwordForm.password"
            type="password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPasswordChange">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Workbench',
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };

    return {
      username: localStorage.getItem('accountName') || '用户',
      activeMenu: '',
      dialogVisible: false,
      passwordForm: {
        accountName: '',
        oldPassword: '',
        password: '',
        confirmPassword: ''
      },
      user: {
        id: '',
        accountName: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      menuList: []
    };
  },
  methods: {
    // 菜单选择处理
    handleSelect(index, indexPath) {
      console.log('Selected menu:', index, indexPath);
      this.activeMenu = index;
      if (index) {
        this.$router.push(index).catch(err => {
          if (err.name !== 'NavigationDuplicated') {
            throw err;
          }
        });
      }
    },

    // 菜单展开处理
    handleOpen(key, keyPath) {
      console.log('Menu opened:', key, keyPath);
    },

    // 菜单关闭处理
    handleClose(key, keyPath) {
      console.log('Menu closed:', key, keyPath);
    },

    // 下拉菜单命令处理
    handleCommand(command) {
      if (command === 'changePassword') {
        this.dialogVisible = true;
      } else if (command === 'logout') {
        this.handleLogout();
      }
    },

    // 退出登录
    handleLogout() {
      this.$confirm('确认退出登录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          localStorage.clear();
          this.$router.push('/');
          this.$message.success('退出成功');
        })
        .catch(() => {});
    },

    // 提交密码修改
    submitPasswordChange() {
      this.$refs.passwordForm.validate(async (valid) => {
        if (!valid) return;

        try {
          this.passwordForm.accountName = this.username;
          const response = await this.$axios.post('/api/user-server/user/changePassword', this.passwordForm);
          
          if (response.data.code === 200) {
            this.$message.success('密码修改成功，请重新登录');
            this.dialogVisible = false;
            this.handleLogout();
          } else {
            this.$message.error(response.data.msg || '密码修改失败');
          }
        } catch (error) {
          console.error('Change password error:', error);
          this.$message.error('密码修改失败，请重试');
        }
      });
    },

    // 查询用户菜单
    async queryUserMenu() {
      try {
        const response = await this.$axios.post("api/user-server/menu/queryMenuByRole", {
          id: localStorage.getItem('userId')
        });
        
        console.log('Menu response:', response.data);
        
        if (response.data.code === 200) {
          this.menuList = response.data.data;
        } else if (response.data.code === 2008) {
          this.$message.error('该用户当前无任何权限，请联系管理员');
        }
      } catch (error) {
        console.error('Query menu error:', error);
        this.$message.error('获取菜单失败，请重试');
      }
    }
  },
  created() {
    this.queryUserMenu();
    this.username = localStorage.getItem('accountName') || '用户';
    this.user.id = localStorage.getItem('userId');
    
    // 设置当前激活的菜单
    this.activeMenu = this.$route.path;
  }
};
</script>

<style scoped>
.workbench-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: #303133;
}

.header-right {
  cursor: pointer;
}

.main-container {
  flex: 1;
  overflow: hidden;
}

.aside {
  background-color: #001529;
  height: 100%;
}

.el-menu {
  border-right: none;
}

.main-content {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
  overflow-y: auto;
}

.el-dropdown-link {
  color: #409EFF;
  cursor: pointer;
}

.dialog-footer {
  text-align: right;
}
</style>